<template>
  <div class="order-history-container">
    <h2 class="title">我的订单</h2>

    <div v-if="loading" class="loading-container">
      <el-icon class="loading-icon">
        <Loading/>
      </el-icon>
      <span>加载中...</span>
    </div>

    <div v-else-if="orders.length === 0" class="empty-container">
      <el-icon class="empty-icon">
        <Box/>
      </el-icon>
      <p>暂无订单记录</p>
    </div>

    <div v-else class="order-list">
      <div v-for="order in orders" :key="order.orderId" class="order-card">
        <div class="order-header">
          <span class="order-id">订单号: {{ order.orders.orderId }}</span>
            <span class="order-status" :class="getStatusClass(order.orders.status)">
              {{ getStatusText(order.orders.status) }}
            </span>
          </div>

        <div class="order-business">
          <el-icon>
            <Shop/>
          </el-icon>
          <span>{{ order.business.businessName || '未知商家' }}</span>
        </div>

        <div class="order-items">
          <div v-for="(item, index) in order.orderRows" :key="index" class="order-item">
            <span class="item-name">{{ item.foodName }}</span>
            <span class="item-quantity">×{{ item.quantity }}</span>
            <span class="item-price">¥{{ item.rowPrice.toFixed(2) }}</span>
          </div>
        </div>

        <div class="order-footer">
          <div class="order-total">
            合计: <span class="total-price">¥{{ calculateTotal(order.orderRows).toFixed(2) }}</span>
          </div>
          <div class="order-time">
            {{ formatTime(order.createTime) }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {Loading, Shop, Box} from '@element-plus/icons-vue';
import axios from 'axios';
import {ElMessage} from 'element-plus';
import {useRouter} from "vue-router";

const orders = ref([]);
const loading = ref(true);
const router = useRouter()
// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '未完成',
    1: '已完成'
  };
  return statusMap[status] || '未知状态';
};

// 修改后的获取订单状态对应的CSS类
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-pending',
    1: 'status-completed'
  };
  return classMap[status] || '';
};

// 计算订单总价
const calculateTotal = (orderRows) => {
  return orderRows.reduce((total, item) => total + (item.rowPrice * item.quantity), 0);
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    const wechatId = localStorage.getItem('wechat_id') || '';
    console.log(wechatId)
    if (!wechatId) {
      ElMessage.error('未获取到用户信息，请重新登录');
      return;
    }

    const access_token = localStorage.getItem('access_token');
    const response = await axios.get(`http://localhost:8080/order/list/${wechatId}`, {
      headers: {
        'Authorization': `Bearer ${access_token}`
      }
    });

    console.log(response.data)
    if (response.data && Array.isArray(response.data)) {
      orders.value = response.data;
    } else {
      orders.value = [];
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
    orders.value = [];
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  const token = localStorage.getItem('access_token');
  if (!token) {
    ElMessage.error('请先登录');
    router.push('/login');
  } else {
    fetchOrders();
  }
});
</script>

<style scoped>
.order-history-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.title {
  text-align: center;
  margin-bottom: 24px;
  color: #333;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-icon {
  font-size: 32px;
  margin-bottom: 16px;
  animation: rotating 2s linear infinite;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.order-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.order-id {
  font-size: 14px;
  color: #666;
}

.order-status {
  font-size: 14px;
  padding: 4px 8px;
  border-radius: 4px;
}

.status-pending {
  background-color: #fff6e6;
  color: #ff9900;
}

.status-completed {
  background-color: #f6ffed;
  color: #52c41a;
}

.order-business {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  color: #333;
  font-size: 16px;
}

.order-business .el-icon {
  margin-right: 8px;
  color: #666;
}

.order-items {
  margin-bottom: 12px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
}

.order-item:last-child {
  border-bottom: none;
}

.item-name {
  flex: 1;
}

.item-quantity {
  width: 60px;
  text-align: center;
}

.item-price {
  width: 80px;
  text-align: right;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px solid #eee;
}

.order-total {
  font-weight: bold;
}

.total-price {
  color: #ff4d4f;
  font-size: 18px;
}

.order-time {
  font-size: 12px;
  color: #999;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>